package com.class05.mapper.impl;

import com.class05.domain.Student;
import com.class05.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public class StudentMapperImpl implements StudentMapper {


    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void insert(Student student) {
        Integer update = jdbcTemplate.update("insert into students values(?,?,?,?,?)"
                ,student.getId(),student.getName(),
                student.getGender(),student.getAge(),student.getClasses());
        if (update > 0){
            System.out.println("插入成功");
        }
    }
    @Override
    public Student selectById(Integer id) {
        String sql = "select * from students where id= ?";
        List<Student> studentList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class), id);
//        获取第一条数据
//        Student student = studentList.get(0);
//        先获取stream流，再获取第一个元素
        Optional<Student> first = studentList.stream().findFirst();
        return first.get();
    }
}
